import axios  from "axios"
import {ElMessage} from "element-plus"
import {router} from "./router/index.js";
import store from '@/store/index.js'

axios.defaults.baseURL = "http://localhost:8081"

const request = axios.create({
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})
request.interceptors.request.use(config => {
    config.headers['authorization'] = localStorage.getItem("token") // 请求头带上token
    return config
})

request.interceptors.response.use(res => {

        let resp = res.data;
        console.log(res)
        console.log(resp)
        if (resp.code === 200) {
            return resp;
        } else {
            ElMessage.error(resp.msg? resp.msg: "系统异常")
            return resp;
        }
    },
    error => {
        if(error.response.status === 401) {

            router.push("/login")
            store.commit("resetState")
            store.commit("resetUserState")
        }
        ElMessage.error(error.message)
        return Promise.reject(error)
    }
)
export default request






